package hesso.smartdraw.ch;

import java.util.ArrayList;

import hesso.smartdraw.ch.db.DBHelper;
import hesso.smartdraw.ch.db.SyncDbAndDb;
import hesso.smartdraw.ch.model.Building;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class BuildingScreen extends Activity {

	private int userId;

	private String[] listView;
	private ArrayList<Building> buildings;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.buildingscreen);
		
		final Bundle extras = getIntent().getExtras();
		this.userId = extras.getInt("userId");
		
    	
    	SyncDbAndDb syncDb = SyncDbAndDb.getInstance();
    	
//    	syncDb.startProgram(userId);

		DBHelper dbHelper = DBHelper.getInstance(this);

		buildings = dbHelper.getBuildingsByUserId(userId);

		listView = new String[buildings.size()];

		for( int i = 0; i < listView.length; i++) {

			listView[i] = buildings.get(i).getName();
		}

		ListView buildingListView = (ListView)findViewById(R.id.listBuilding);

		buildingListView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listView));

		buildingListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				
				onItemClickEvent(pos);
			}


		});

		buildingListView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener 
				(){ 
			@Override 
			public boolean onItemLongClick(AdapterView<?> av, View v, int 
					pos, long id) { 
 
				onItemLongClickEvent(pos);
				return true; 
			} 
		}); 

		final Button button = (Button) findViewById(R.id.buttonNewBuilding);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				newBuilding();
			}
		});
	}

	public void newBuilding() {
		Intent intent = new Intent(this,EditBuildingScreen.class);
		intent.putExtra("userId", userId);
		intent.putExtra("buildingId", -1);
		startActivity(intent);
	}
	
	public void onItemClickEvent(int pos) {
		Intent intent = new Intent(this,DrawWallScreen.class);
		intent.putExtra("buildingId", buildings.get(pos).getId());
		intent.putExtra("level", 0);
		startActivity(intent);
	}
	
	public void onItemLongClickEvent(int pos) {
		Intent intent = new Intent(this,EditBuildingScreen.class);
		intent.putExtra("userId", userId);
		intent.putExtra("buildingId", buildings.get(pos).getId());
		startActivity(intent);
	}
}
